import ExpenseBaseModel from './ExpenseBaseModel.js';
import { formatPaymentDate } from '../../date.js';
import Radio from 'backbone.radio';
import {
  strToFloat,
  round,
} from 'math.js';

const ExpenseModel = ExpenseBaseModel.extend({
    defaults:{
      category: null,
      description:"",
      invoice_number: "",
      ht:null,
      tva:null,
      manual_ttc: null,
      tva_rate: null,  // not synced, client-side use only
      ttc_readonly: null, // not synced, client-side use only
      customer_id:null,
      project_id:null,
      business_id:null,
      supplier_id: null,
      fill_mode: 'ht', // not synced, client-side use only
    },
    // Constructor dynamically add a altdate if missing
    // (altdate is used in views for jquery datepicker)
    initialize(options){
      if ((options['altdate'] === undefined)&&(options['date']!==undefined)){
        this.set('altdate', formatPaymentDate(options['date']));
      }

      // API does not return ttc_readonly, we compute it client side
      let ttc_readonly = 0;
      if(this.get('ht') && this.get('tva')) {
        ttc_readonly = round(strToFloat(this.get('ht')) + strToFloat(this.get('tva')));
      }
      this.set('ttc_readonly', ttc_readonly);
      this.config = Radio.channel('config');
      this.facade = Radio.channel('facade');
    },
    // Validation rules for our model's attributes
    validation:{
      type_id:{
        required:true,
        msg:"est requis"
      },
      date: {
        required:true,
        pattern:/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/,
        msg:"est requise"
      },
      ht: {
        required:true,
        pattern: "amount3",
      },
      tva: {
        required:true,
        pattern: "amount3",
      },
      manual_ttc: {
          required: true,
          pattern: 'amount3',
      },
      ttc_readonly: {
        required: true,
        pattern: "amount3",
      },
      tva_rate: {
          required: false,
          pattern: 'amount2',
      },
    },
    total: function(){
      if (this.hasTvaOnMargin()) {
        return strToFloat(this.get('manual_ttc'));
      } else {
        return this.getHT() + this.getTva();
      }
    },
    getTva:function(){
      var result = strToFloat(this.get('tva'));
      return this.getType().computeAmount(result);
    },
    getHT:function(){
      var result = strToFloat(this.get('ht'));
      return this.getType().computeAmount(result);
    },
    getSupplierLabel(){
        let supplier = this.facade.request(
            'get:supplier',
            this.get('supplier_id'),
        );
        if (supplier) {
            return supplier.get('label');
        } else {
            return '';
        }
    },
    isTelType: function() {
      let type = this.getType();

      if (type == undefined) {
        console.warn('Should not happen');
        return false;
      } else {
          return type.get('family') == 'tel';
      }
    },
    hasDeductibleTva: function() {
      let type = this.getType();
      if (type == undefined) {
        return true;
      } else {
        return type.get('is_tva_deductible');
      }
    },
    hasTvaOnMargin: function() {
      let type = this.getType();
      if (type == undefined) {
        return false;
      } else {
        return type.get('tva_on_margin');
      }
    },
    requiresTtcInput() {
        return this.hasTvaOnMargin() || ! this.hasDeductibleTva();
    },
    loadBookMark(bookmark){
        var attributes = _.omit(bookmark.attributes, function(value, key){
            if (_.indexOf(['id', 'cid'], key) > -1){
                return true;
            } else if (_.isNull(value) || _.isUndefined(value)){
                return true;
            }
            return false;
        });
        this.set(attributes);
        this.trigger('set:bookmark');
    },
    isFileLinked(file){
        return this.get('files').includes(file.id);
    },
    linkToFile(file){
        let files = this.get('files');
        if (!this.isFileLinked(file)) {
            files.push(file.id);
        }
        this.set('files', files, {silent: true});
    },
    unlinkFromFile(file){
        let files = this.get('files');
        if (this.isFileLinked(file)) {
            files.splice(files.indexOf(file.id), 1);
        }
        this.set('files', files, {silent: true});
    },
});
export default ExpenseModel;
